<script setup lang="ts">
import type { TableProps } from 'ant-design-vue'

import { onMounted, ref, watch } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { useDebounceFn } from '@vueuse/core'
import { Button, DatePicker, Input, InputNumber, message, Select, Table } from 'ant-design-vue'

import { getPurchaser, getToPurchaseList } from '#/api/spuBom'

import purchase_info from '../purchase_info.vue'
import placeOrder_info from './placeOrder_info.vue'
// 定义组件props并获取props引用
const props = defineProps<{
  data: any
}>()

const NeedPurchaseList = ref([])
// 监听data变化，更新表格数据
watch(
  () => props.data,
  (newData) => {
    if (newData) {
      initData(props.data.id)
    }
  },
  { immediate: true },
)

const columns: any = ref([
  {
    title: 'BOM类型',
    dataIndex: 'bom_name',
    key: 'bom_name',
    align: 'center',
    width: 200,
    resizable: true,
  },
  {
    title: '预计用量',
    dataIndex: 'single_piece',
    key: 'single_piece',
    align: 'center',
    width: 100,
    resizable: true,
  },
  {
    title: '唛架用量',
    dataIndex: 'marker_single_piece',
    key: 'marker_single_piece',
    align: 'center',
    width: 100,
    resizable: true,
  },
  {
    title: '实际面料',
    resizable: true,
    children: [
      {
        title: '面料名称',
        dataIndex: 'material_name',
        key: 'material_name',
        align: 'center',
        width: 400,
        ellipsis: true,
        resizable: true,
      },
      {
        title: '本次供应商',
        dataIndex: 'SupplyNa',
        key: 'SupplyNa',
        align: 'center',
        width: 300,
        resizable: true,
      },
      {
        title: '本次单价',
        dataIndex: 'price',
        key: 'price',
        align: 'center',
        resizable: true,
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        align: 'center',
        resizable: true,
      },
    ],
  },
  {
    title: '是否厂供',
    dataIndex: 'is_factory_supply',
    key: 'is_factory_supply',
    align: 'center',
    resizable: true,
  },
  {
    title: '算料件数',
    dataIndex: 'computedNum',
    key: 'computedNum',
    align: 'center',
    resizable: true,
  },

  {
    title: '需求量',
    dataIndex: 'need_num',
    key: 'need_num',
    align: 'center',
    resizable: true,
  },
  {
    title: '已下数量',
    dataIndex: 'scope',
    key: 'scope',
    align: 'center',
    resizable: true,
  },

  {
    title: '下单明细',
    dataIndex: 'purchase_times',
    key: 'purchase_times',
    align: 'center',
    resizable: true,
  },
  {
    title: '未下数量',
    dataIndex: 'no_purchase_num',
    key: 'shou_num',
    align: 'center',
    resizable: true,
  },
])
const columns1: any = ref([
  {
    title: 'BOM类型',
    dataIndex: 'bom_name',
    key: 'bom_name',
    align: 'center',
    resizable: true,
  },
  {
    title: '实际面料',
    resizable: true,
    children: [
      {
        title: '面料名称',
        dataIndex: 'material_name',
        key: 'material_name',
        align: 'center',
        width: 400,
        ellipsis: true,
        resizable: true,
      },
      {
        title: '本次供应商',
        dataIndex: 'SupplyNa',
        key: 'SupplyNa',
        align: 'center',
        resizable: true,
      },
      {
        title: '单价',
        dataIndex: 'price',
        key: 'price',
        resizable: true,
        align: 'center',
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        resizable: true,
        align: 'center',
      },
    ],
  },
  {
    title: '采购员',
    dataIndex: 'purchase_user',
    key: 'purchase_user',
    align: 'center',
    resizable: true,
  },
  {
    title: '下单数量',
    dataIndex: 'num',
    key: 'num',
    align: 'center',
    resizable: true,
  },
  {
    title: '交期',
    dataIndex: 'dead_line',
    key: 'dead_line',
    align: 'center',
    resizable: true,
  },
  {
    title: '其他结算方式备注',
    dataIndex: 'other_pay_remark',
    key: 'other_pay_remark',
    align: 'center',
    resizable: true,
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    align: 'center',
    resizable: true,
  },
])

function initData(id: any) {
  const param = {
    bomId: id,
  }
  getToPurchaseList(param).then((response) => {
    const list = response.data.data.list
    NeedPurchaseList.value = list.map((item: any) => ({
      ...item,
      num: item.no_purchase_num,
    }))
  })
}

const [purchase_infoModal, purchase_infoModalApi] = useVbenModal({
  connectedComponent: purchase_info,
})

function openModel(record: any) {
  purchase_infoModalApi.setData({ data: record }).open()
}

function refresh() {
  initData(props.data.id)
}

const selectRows: any = ref([])
const rowSelect: TableProps['rowSelection'] = {
  onChange: (selectedRowKeys: any, selectedRows: any) => {
    selectRows.value = selectedRows
  },
}

const Options = ref([])
const loading = ref(false)
const handleSupplySearch = useDebounceFn(async (keyword) => {
  loading.value = true
  try {
    const res = await getPurchaser({
      quick_search: keyword || '',
      page: 1,
      limit: 9999,
      group_id: 7,
      initKey: 'id',
      select: true,
    })

    Options.value = res.data.data.list.map((it) => ({
      label: it.realname,
      value: it.id,
    }))
  } finally {
    loading.value = false
  }
}, 300)

// 第一次打开下拉就触发一次空搜索，把全部选项拿回来
const handleSupplyDropdown = (open) => {
  if (open && Options.value.length === 0) {
    handleSupplySearch('')
  }
}

// 判断行是否满足条件，如果满足则返回特殊样式类
const getRowClassName = (record) => {
  if (record.not_caigou === 0 && record.cuted_num > 0 && record.purchase_need_diff_num < 0) {
    return 'red-text-row'
  }
  return ''
}

function placeOrder() {
  if (selectRows.value.length > 0) {
    placeOrder_infoModalApi
      .setData({
        data: selectRows.value,
        id: props.data.id,
        purchase_id: props.data.purchase_id,
      })
      .open()
  } else {
    message.error('请选择面料')
  }
}

const [placeOrder_infoModal, placeOrder_infoModalApi] = useVbenModal({
  connectedComponent: placeOrder_info,
})
onMounted(() => {
  handleSupplySearch('')
})
</script>

<template>
  <div style="width: 100%; display: flex; justify-content: flex-end; font-size: 18px">
    <strong>应采购 :</strong>
  </div>
  <Table
    class="mb-2 w-full"
    :scroll="{ x: '100%', y: 'calc(25vh)' }"
    row-key="id"
    :row-selection="rowSelect"
    bordered
    :data-source="NeedPurchaseList"
    :columns="columns"
    :pagination="false"
    size="small"
    @resize-column="(w: any, col: any) => (col.width = w)"
    :row-class-name="getRowClassName"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'scope'">
        <template v-if="record.sku_id > 0 || record.purchase_num > 0">
          <div style="color: #409eff" @click="openModel(record)">
            <u>{{ record.purchase_num }}</u>
          </div>
        </template>
      </template>

      <template v-if="column.dataIndex === 'is_factory_supply'">
        {{ record.is_factory_supply === 1 ? '是' : '否' }}
      </template>
    </template>
  </Table>
  <div style="width: 100%; display: flex; justify-content: flex-end; font-size: 18px">
    <strong>已选 :</strong>
  </div>

  <Table class="w-full" bordered :data-source="selectRows" :columns="columns1" :pagination="false" size="small" @resize-column="(w: any, col: any) => (col.width = w)" :scroll="{ x: '100%', y: 'calc(25vh)' }">
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'purchase_user'">
        <Select
          v-model:value="record.purchase_user"
          show-search
          allow-clear
          style="width: 100%; height: 100%"
          paceholder="请输入"
          :filter-option="false"
          :options="Options"
          :loading="loading"
          @search="handleSupplySearch"
          @dropdown-visible-change="handleSupplyDropdown"
        />
      </template>
      <template v-if="column.dataIndex === 'num'">
        <InputNumber v-model:value="record.num" />
      </template>
      <template v-if="column.dataIndex === 'dead_line'">
        <DatePicker format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-model:value="record.dead_line" />
      </template>

      <template v-if="column.dataIndex === 'other_pay_remark'">
        <Input v-model:value="record.other_pay_remark" />
      </template>
      <template v-if="column.dataIndex === 'remark'">
        <Input v-model:value="record.remark" />
      </template>
    </template>
  </Table>
  <div style="width: 100%; display: flex; justify-content: flex-end; font-size: 18px">
    <Button type="primary" @click="placeOrder()">下单</Button>
  </div>

  <purchase_infoModal @refresh="refresh()" />
  <placeOrder_infoModal @refresh="refresh()" />
</template>

<style scoped>
:deep(.red-text-row) {
  color: red !important;
}

/* 确保表格单元格中的文本也应用红色 */
:deep(.red-text-row td) {
  color: red !important;
}

/* 确保表格内容中的所有文本元素都应用红色 */
:deep(.red-text-row span),
:deep(.red-text-row div),
:deep(.red-text-row u) {
  color: red !important;
}
</style>
